package ${initProjectVo.packageName}.security.filter;



import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

public class CustomerUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

    if(!"POST".equals(request.getMethod())){
        throw  new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
    }
    if(request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE) || request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_UTF8_VALUE)){
        try {
            Map<String,String> map = objectMapper.readValue(request.getInputStream(), Map.class);
            String username = map.get(getUsernameParameter());
            String password = map.get(getPasswordParameter());
            // 从Map对象中分别提取用户名和密码
            // 构造成UsernamePasswordAuthenticationToken对象
            UsernamePasswordAuthenticationToken authRequest
                = new UsernamePasswordAuthenticationToken(username,password);
            setDetails(request,authRequest);
        // 调用AuthenticationManager的 authticate()方法完成认证操作
        return this.getAuthenticationManager().authenticate(authRequest);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //如果不是json格式，那么按照父类的表单登录逻辑处理
        return super.attemptAuthentication(request,response);
    }

    @Override
    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        super.setAuthenticationManager(authenticationManager);
    }
}
